package com.manfred.JNDIStudy.directory;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import com.manfred.JNDIStudy.attri.GetAllAttrs;
import com.manfred.domain.Fruit;

/**
 * Demonstrates how to add a binding and its attributes to a context. (Use
 * Rebind example to overwrite binding; use Unbind to remove binding.)
 *
 * usage: java Bind
 */

class Bind {
	public static void main(String[] args) {

		// Set up the environment for creating the initial context
		Hashtable env = new Hashtable(11);
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://localhost:10389/o=JNDITutorial");

		try {
			// Create the initial context
			DirContext ctx = new InitialDirContext(env);

			// Create object to be bound
			Fruit fruit = new Fruit("orange");

			// Create attributes to be associated with object
			Attributes attrs = new BasicAttributes(true); // case-ignore
			Attribute objclass = new BasicAttribute("objectclass");
			objclass.add("top");
			objclass.add("organizationalUnit");
			attrs.put(objclass);

			// Perform bind
			ctx.bind("ou=Fruits", fruit, attrs);

			// Check that it is bound
			Object obj = ctx.lookup("ou=Fruits");
			System.out.println(obj);

			// Get its attributes
			Attributes retattrs = ctx.getAttributes("ou=Fruits");
			GetAllAttrs.printAttrs(retattrs);

			// Close the context when we're done
			ctx.close();
		} catch (NamingException e) {
			System.out.println("Operation failed: " + e);
		}
	}
}